package ustc.xiaoyang.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import ustc.xiaoyang.mapper.OperateLogMapper;
import ustc.xiaoyang.pojo.OperateLog;
import ustc.xiaoyang.utils.ThreadLocalUtils;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 记录操作日志的切面
 */
@Aspect
@Component
public class RecordLogAspect {
    private OperateLogMapper operateLogMapper;
    public RecordLogAspect(OperateLogMapper operateLogMapper) {
        this.operateLogMapper = operateLogMapper;
    }
    @Pointcut("@annotation(ustc.xiaoyang.annotation.RecordLog)")
    public void pointcut(){}
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        long cost = end - start;
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(getCurrentEmpId());
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        operateLog.setMethodName(joinPoint.getSignature().getName());
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        operateLog.setReturnValue(result.toString());
        operateLog.setCostTime(cost);
        operateLogMapper.insert(operateLog);
        return result;
    }

    private Integer getCurrentEmpId() {
        return ThreadLocalUtils.getCurrentEmpId();
    }

}
